package com.ys.web.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ys.WebConstants;
import com.ys.extend.utils.TimeUtil;
import com.ys.web.dao.CommonDao;
import com.ys.web.entity.BestKeyword;
import com.ys.web.entity.Industry;
import com.ys.web.pojo.BestKeywordInfo;
import com.ys.web.remotemodel.RemoteIndustryInfo;
import com.ys.web.service.BestKeywordService;
import com.ys.web.ws.service.ManageIndustryService;

/**
 * 最优行业关键词 -Service-实现类
 * @author wdj
 *
 */
@Service
@Transactional
public class BestKeywordServiceImpl implements BestKeywordService {

	@Autowired
	private CommonDao commonDao;	
	@Resource
	private ManageIndustryService manageIndustryService;
	
/*	***
	 * 根据行业查询最优行业关键词
	 * @param industryId 行业id
	 *  @param page 当前页码
	 * @return 最优行业关键词列表
	 *//*
	@Override
	public List<BestKeywordInfo> getBestKeywordByIndustry(Integer industryId, int page) {
		List<BestKeywordInfo> list = new ArrayList<>();
		
		DetachedCriteria dc = DetachedCriteria.forClass(BestKeyword.class);	
		if(industryId != null) {
			Criterion cr = Restrictions.eq("industryId", industryId);
			dc.add(cr);
		}
		List<BestKeyword> listBK = commonDao.pageList(dc, WebConstants.MAX_REQUEST_ROW_EACH*(page-1), WebConstants.MAX_REQUEST_ROW_EACH_PROMOTE);
		for (BestKeyword bestKeyword : listBK) {
			try {
				BestKeywordInfo bestKeywordInfo = new BestKeywordInfo();			
				BeanUtils.copyProperties(bestKeyword, bestKeywordInfo);
				Industry industry = commonDao.getEntity(Industry.class, bestKeywordInfo.getIndustryId());
				bestKeywordInfo.setIndustryName(industry.getIndustryName());				
				bestKeywordInfo.setSaveDate(TimeUtil.getFormatDate(bestKeyword.getSaveDate(), "yyyy-MM-dd HH:mm:ss"));
				
				list.add(bestKeywordInfo);
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}	
		
		return list;
	}
*/	
	/**
	 * 根据行业查询最优行业关键词，相同标题的关键词合并
	 * @param industryId 行业id
	 *  @param page 当前页码
	 * @return 最优行业关键词列表
	 */
	@Override
	public List<BestKeywordInfo> getBestKeywordByIndustry(Integer industryId, int page) {
		List<BestKeywordInfo> list = new ArrayList<>();
		Set<String> titleSet = new HashSet<>();
		
		DetachedCriteria dc = DetachedCriteria.forClass(BestKeyword.class);	
		if(industryId != null) {
			Criterion cr = Restrictions.eq("industryId", industryId);
			dc.add(cr);
		}
		List<BestKeyword> listBK = commonDao.pageList(dc, WebConstants.MAX_REQUEST_ROW_EACH*(page-1), WebConstants.MAX_REQUEST_ROW_EACH_PROMOTE);
		if(listBK!=null && !listBK.isEmpty()) {
			//方案标题去重复
			for (BestKeyword bestKeywordSet : listBK) {
				//行业 + 方案标题
				titleSet.add(bestKeywordSet.getIndustryId() + "," + bestKeywordSet.getTitle());
			}
			//根据行业和标题，再次查询
			Iterator ite = titleSet.iterator();
			while(ite.hasNext()) {
				try {
					String[] setArr = ite.next().toString().split(","); //划分： 行业 、 方案标题				
					String hql = " from BestKeyword where industryId = ? and title = ?";
					List<BestKeyword> titleList = commonDao.findHql(hql, Integer.valueOf(setArr[0]),setArr[1]);
					
					BestKeywordInfo bestKeywordInfo = new BestKeywordInfo();
					StringBuffer promotionKeywordList = new StringBuffer();
					StringBuffer keywordSearchList = new StringBuffer();
					//同一行业下，相同标题的关键词合并
					for (BestKeyword bestKeyword : titleList) {
						promotionKeywordList.append(bestKeyword.getPromotionKeyword() + "\n");
						keywordSearchList.append(bestKeyword.getKeywordSearch() + "\n");
						BeanUtils.copyProperties(bestKeyword, bestKeywordInfo);
						bestKeywordInfo.setSaveDate(TimeUtil.getFormatDate(bestKeyword.getSaveDate(), "yyyy-MM-dd HH:mm:ss"));
					}
					bestKeywordInfo.setPromotionKeywordList(promotionKeywordList.toString());
					bestKeywordInfo.setKeywordSearchList(keywordSearchList.toString());
//				    Industry industry = commonDao.getEntity(Industry.class, bestKeywordInfo.getIndustryId());
					RemoteIndustryInfo industry = manageIndustryService.getEntity(bestKeywordInfo.getIndustryId());
					bestKeywordInfo.setIndustryName(industry.getIndustry());				
					
					list.add(bestKeywordInfo);				
				} catch (Exception e) {
					e.printStackTrace();
				}
			}	
		}
		
		return list;
	}
	
	/**
	 * 批量保存新增的最优行业关键词，不存在，才保存新增
	 * @param bestKeyword
	 * @return true:保存成功；false：存在相同数据，保存失败
	 */
	@Override
	public Boolean batchAdd(BestKeyword[] bestKeywordList) {
		Date saveDate = TimeUtil.getNowTime();
		int i = 0;
		for (BestKeyword bestKeyword : bestKeywordList) {
			Boolean ifExist = ifExist(bestKeyword.getIndustryId(), bestKeyword.getKeywordSearch());
			//不存在相同，才保存新增
			if(!ifExist) {
				bestKeyword.setSaveDate(saveDate);
				commonDao.save(bestKeyword);			
			}
			else{
				i++;
			}
		}
		
		//若全部都不保存，则提示“存在相同数据，保存失败”
		if(i == bestKeywordList.length) {
			return false;
		}
		else {
			return true;
		}
	}
	/**
	 * 判断是否存在
	 * @param industryId 行业id
	 * @param keywordSearch 搜索关键词
	 * @return true：存在；false：不存在
	 */
	private Boolean ifExist(Integer industryId, String keywordSearch) {
		String hql = " from BestKeyword where industryId = ? and keywordSearch = ?";
		List<BestKeyword> list = commonDao.findHql(hql, industryId,keywordSearch);
		if(list != null && list.size()>0) {
			return true;
		}
		else {
			return false;
		}
	}
	
	/**
	 * 删除同一行业下同一标题的“最优行业关键词”
	 * @param id “最优行业关键词”id
	 */
	@Override
	public void deleteBestKeywordByTitle(Integer id) {
		BestKeyword bestKeyword = commonDao.getEntity(BestKeyword.class, id);
		String hql = " from BestKeyword where industryId = ? and title = ?";
		List<BestKeyword> list = commonDao.findHql(hql, bestKeyword.getIndustryId(),bestKeyword.getTitle());
		//批量删除同一行业下同一标题的“最优行业关键词”
		commonDao.deleteAllEntitie(list);		
	}
	
	/**
	 * 修改最优行业关键词
	 * @param bestKeyword
	 */
	@Override
	public void update(BestKeyword bestKeyword) {
		commonDao.updateEntitie(bestKeyword);
	}	
	
}
